<?php
require_once 'db_config.php';
$qid = $_GET["qid"];
$ans = $_GET['ans'];
session_start();
$userid = $_SESSION['userid'];
if (!isset($userid)) $userid = 1;
if (isset($qid))
{
    $query = "select * from question";
    $result = mysql_query($query);


    if ($qid == mysql_num_rows($result)) {
        $query = "select * from question_result where user_id = ".$userid;
        $result = mysql_query($query);
        $result = mysql_fetch_array($result);
        $total = $result['total'];
        $query = "select * from question where id = ".($qid - 1);
        $result = mysql_query($query);
        $result = mysql_fetch_array($result);
        if ($ans == $result['answer']) {
            $total++;
        }
        echo '
        <h1>Ваш результат '.$total.'
        </h1>
        ';
    } else {
        // check if user passing test first time

        if ($qid == 0) {
            $query = "DELETE FROM question_result WHERE user_id = ".$userid."";
            $result = mysql_query($query);
        }

        $query = "select * from question_result where user_id = ".$userid;
        $result = mysql_query($query);
        $total = 0;


        if (mysql_num_rows($result) == 0) {
            $query = "insert into question_result values(".$userid.", 0)";
            $result = mysql_query($query);
        } else {
            $flag = 0;
            $result = mysql_fetch_array($result);
            $total = $result['total'];
            if ($qid > 0) {
                $query = "select * from question where id = ".$qid;
                $result = mysql_query($query);
                $result = mysql_fetch_array($result);

                if ($ans == $result['answer']) {
                    $total++;
                }
            }

            $query = "update question_result set total = ".$total." WHERE user_id = ".$userid;
            $result = mysql_query($query);
        }
        $query = "select * from question where id=".$qid;
        $result = mysql_query($query);
        if (mysql_num_rows($result) >= 1) {
            $result = mysql_fetch_array($result);
            $qtitle = $result["title"];
            $q1 = $result["q1"];
            $q2 = $result["q2"];
            $q3 = $result["q3"];
    ?>

            <section>
                <form class="ac-custom ac-radio ac-fill" autocomplete="off">

                    <h2><?php echo $qtitle;?></h2>
                    <ul>
                        <li><input id="r7" name="r1"type="radio" data-col="1"><label for="r7"><?php echo $q1;?></label></li>
                        <li><input id="r8" name="r1" type="radio" data-col="2"><label for="r8"><?php echo $q2;?></label></li>
                        <li><input id="r9" name="r1"type="radio" data-col="3"><label for="r9"><?php echo $q3;?></label></li>

                    </ul>
                </form>
            </section>

    <?php
    }
    }
}
?>